package edu.scau.system.service;

import edu.scau.system.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class UserAuthServiceImpl implements IUserAuthService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return token
     * @throws AuthenticationException
     */
    @Override
    public String login(String username, String password) throws AuthenticationException {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //SecurityContextHolder存储当前用户的身份验证信息------->ThreadLocal识别本次线程的请求
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //如果密码匹配，则 AuthenticationProvider 创建一个新的 Authentication 对象（通常是 UsernamePasswordAuthenticationToken 的一个实例），并将 UserDetails 对象设置为其 principal 属性，将用户的权限设置为其 authorities 属性。
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.generateToken(loginUser);
    }

    /**
     * 获取当前登录的用户信息
     * @return 登录用户信息
     */
    public LoginUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
            return (LoginUser) authentication.getPrincipal();
        }

        return null; // 或者抛出异常，表示用户未登录
    }
}